package com.xxb.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.xxb.entity.Product;
import com.xxb.entity.Type;
import com.xxb.util.DBHelp;
import com.xxb.util.Rowmapper;

public class ProductDao {
	
	private DBHelp<Product> db = new DBHelp<Product>();
	public int save(Product p){
		String sql = "insert into t_product(productname,price,mprice,size,color,pic,content,tid,CODE,information) values(?,?,?,?,?,?,?,?,?,?)";
		return db.executeSQL(sql, p.getProductname(),p.getPrice(),p.getMprice(),p.getSize(),p.getColor(),p.getPic(),p.getContent(),p.getTid(),p.getCode(),p.getInformation());
	}
	
	public int delete(int id) {
		String sql = "delete from t_product where id = ?";
		return db.executeSQL(sql, id);
	}
	
	public int update(Product p){
		String sql ="update t_product set productname=?,price=?,mprice=?,size=?,color=?,pic=?,content=?,tid=?,CODE=?,information=? where id=?";
		return db.executeSQL(sql, p.getProductname(),p.getPrice(),p.getMprice(),p.getSize(),p.getColor(),p.getPic(),p.getContent(),p.getTid(),p.getCode(),p.getInformation(),p.getId());
	}
	public List<Product> fintBytid(int tid){
		String sql = "SELECT t_product.id AS pid ,productname,price,mprice,size,color,pic,content,tid,CODE,information,typename FROM t_product LEFT JOIN t_type ON t_product.tid=t_type.id where tid=? ";
		return db.quertyList(sql, new ProductRowmapper(),tid);
	}
	
	public Product findByid(int id){
		String sql = "SELECT t_product.id AS pid ,productname,price,mprice,size,color,pic,content,tid,CODE,information,typename FROM t_product LEFT JOIN t_type ON t_product.tid=t_type.id where t_product.id=? ";
		return db.queryObject(sql, new ProductRowmapper(),id);
	}
	public List<Product> findAll(){
		String sql = "SELECT t_product.id AS pid ,productname,price,mprice,size,color,pic,content,tid,CODE,information,typename FROM t_product LEFT JOIN t_type ON t_product.tid=t_type.id ";
		return db.quertyList(sql, new ProductRowmapper());
	}
	
	private class ProductRowmapper implements Rowmapper<Product>{

		public Product mapRow(ResultSet rs) throws SQLException {
			
			Product p = new Product();
			p.setColor(rs.getString("color"));
			p.setContent(rs.getString("content"));
			p.setPrice(rs.getFloat("price"));
			p.setId(rs.getInt("pid"));
			p.setMprice(rs.getFloat("mprice"));
			p.setPic(rs.getString("pic"));
			p.setCode(rs.getString("code"));
			p.setInformation(rs.getString("information"));
			p.setTid(rs.getInt("tid"));
			p.setProductname(rs.getString("productname"));
			p.setSize(rs.getString("size"));
			
			Type type = new Type();
			type.setId(rs.getInt("tid"));
			type.setTypename(rs.getString("typename"));
			p.setType(type);
			
			return p;
		}
		
		
	}
	
}
